<?php


namespace app\controller\api;


use app\BaseController;
use app\models\goods\GoodsCartModel;
use app\models\goods\GoodsModel;
use app\models\goods\GoodsSkuModel;
use app\models\shop\ShopModel;
use app\services\config\ConfigService;
use think\facade\Db;

class CartController extends BaseController
{
    /**
     * 购物车
     * @return \think\response\Json
     */
    public function getList()
    {
        try {
            $userId = $this->request->userId;

            $list = GoodsCartModel::where('user_id', $userId)->select()->toArray();
            $shop_ids = array_column($list,'shop_id');
            $shop_data = (new ShopModel())->where('id','in',$shop_ids)->column('id,shop_name,img','id');
//            $logo = ConfigService::getConfigValue('logo');
//            $shop_data[0] = ['id'=>0,'shop_name' => '自营','img' => $logo];

            $config_shop = ConfigService::getConfigValueArray(['shop_name','shop_logo']);
            $shop_data[0] = ['id'=>0,'shop_name' => $config_shop['shop_name'],'img' => $config_shop['shop_logo']];

            $data = [];
            foreach ($list as &$value) {
                $goodsInfo = GoodsModel::where('id', $value['goods_id'])->find();
                $value['shop_id'] = intval($value['shop_id']);
                $value['goods_name'] = $goodsInfo['name'];
                $value['sell_price'] = $goodsInfo['sell_price'];
                $value['market_price'] = $goodsInfo['market_price'];
                $value['goods_image'] = $goodsInfo['image'];
                $value['stock'] = $goodsInfo['stock'];
                $goodsSku = GoodsSkuModel::where('id', $value['goods_sku_id'])->find();
                if($goodsSku){
                    $value['sku_name'] = $goodsSku['name'];
                    $value['sku_sell_price'] = $goodsSku['sell_price'];
                    $value['sku_market_price'] = $goodsSku['market_price'];
                    $value['sku_stock'] = $goodsSku['stock'];
                }else{
                    $value['sku_name'] = '';
                    $value['sku_sell_price'] = "0";
                    $value['sku_market_price'] = "0";
                    $value['sku_stock'] = "0";
                }

                if(isset($data[$value['shop_id']])){
                    $data[$value['shop_id']]['goods'][] = $value;
                }else{
                    $data[$value['shop_id']] = [];
                    $data[$value['shop_id']]['shop'] = $shop_data[$value['shop_id']];
                    $data[$value['shop_id']]['goods'] = [$value];
                }
            }
            return $this->success($data);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 购物车
     * @return \think\response\Json
     */
    public function getCount()
    {
        try {
            $userId = $this->request->userId;

            $count = GoodsCartModel::where('user_id', $userId)->count();
            return $this->success(['total' => $count]);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 添加购物车
     * @return \think\response\Json
     */
    public function add()
    {
        try {
            $goodsId = $this->request->param('goods_id');
            $skuId = $this->request->param('sku_id');
            $goodsNum = $this->request->param('goods_num', 1);
            $goodsInfo = GoodsModel::find($goodsId);
            if (!$goodsInfo) {
                throw new \Exception('商品不存在');
            }
            if ($goodsInfo['status'] != 1) {
                throw new \Exception('商品已下架');
            }
            if (!$skuId) {
                throw new \Exception('请选择规格');
            }
            $userId = $this->request->userId;
            $cartInfo = GoodsCartModel::where('user_id', $userId)->where('goods_id', $goodsId)->where('goods_sku_id', $skuId)->find();
            if (!$cartInfo) {
                $model = new GoodsCartModel();
                $model->goods_sku_id = $skuId;
                $model->user_id = $userId;
                $model->goods_id = $goodsId;
                $model->num = $goodsNum;
                $model->shop_id = intval($goodsInfo['shop_id']);
                $model->save();
            } else {
                $cartInfo->num = Db::raw('num+' . $goodsNum);
                $cartInfo->save();
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 更新购物车
     * @return \think\response\Json
     */
    public function edit()
    {
        try {
            $cartId = $this->request->param('cart_id');
            $num = $this->request->param('num', 1);
            $cartInfo = GoodsCartModel::find($cartId);
            if (!$cartInfo) {
                throw new \Exception('信息不存在');
            }
            if ($num <= 0) {
                $cartInfo->delete();
            } else {
                $cartInfo->num = $num;
                $cartInfo->save();
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 删除
     * @return \think\response\Json
     */
    public function del()
    {
        try {
            $cartIds = $this->request->param('cart_ids');
            $userId = $this->request->userId;
            $count = GoodsCartModel::whereIn('id', $cartIds)->where('user_id', $userId)->count();
            if(is_string($cartIds)){
                $cartIds = explode(',',$cartIds);
            }
            if (is_array($cartIds) && $count != count($cartIds)) {
                throw new \Exception("非法请求");
            }
            GoodsCartModel::destroy($cartIds);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}